using Infrastructure.Attribute;
using Infrastructure.Extensions;
using ZR.Model.BaseManage.Dto;
using ZR.Model.BaseManage;
using ZR.Repository;
using ZR.Service.BaseManage.IBaseManageService;
using Infrastructure;

namespace ZR.Service.BaseManage
{
    /// <summary>
    /// 客户信息Service业务层处理
    /// </summary>
    [AppService(ServiceType = typeof(IBaseCustomService), ServiceLifetime = LifeTime.Transient)]
    public class BaseCustomService : BaseService<BaseCustom>, IBaseCustomService
    {
        /// <summary>
        /// 查询客户信息列表
        /// </summary>
        /// <param name="parm"></param>
        /// <returns></returns>
        public PagedInfo<BaseCustomDto> GetPageList(BaseCustomQueryDto parm)
        {
            var predicate = QueryExp(parm);

            var response = Queryable()
                .Where(predicate.ToExpression())
                .ToPage<BaseCustom, BaseCustomDto>(parm);

            return response;
        }


        /// <summary>
        /// 获取详情
        /// </summary>
        /// <param name="CostumId"></param>
        /// <returns></returns>
        public BaseCustom GetInfo(string CostumId)
        {
            var response = Queryable()
                .Where(x => x.CostumId == CostumId)
                .First();

            return response;
        }

        /// <summary>
        /// 添加客户信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public BaseCustom AddBaseCustom(BaseCustom model)
        {
            if (this.Any(it => it.CostumCode == model.CostumCode))
            {
                throw new CustomException($"系统中已包含{model.CostumCode}编码信息");
            }
            return Insertable(model).ExecuteReturnEntity();
        }

        /// <summary>
        /// 修改客户信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int UpdateBaseCustom(BaseCustom model)
        {
            if (this.Any(it => it.CostumCode == model.CostumCode && it.CostumId != model.CostumId))
            {
                throw new CustomException($"系统中已包含{model.CostumCode}编码信息");
            }
            return Update(model, true);
        }

        /// <summary>
        /// 查询导出表达式
        /// </summary>
        /// <param name="parm"></param>
        /// <returns></returns>
        private static Expressionable<BaseCustom> QueryExp(BaseCustomQueryDto parm)
        {
            var predicate = Expressionable.Create<BaseCustom>();

            predicate = predicate.AndIF(!string.IsNullOrEmpty(parm.CostumCode), it => it.CostumCode == parm.CostumCode);
            predicate = predicate.AndIF(!string.IsNullOrEmpty(parm.CostumName), it => it.CostumName.Contains(parm.CostumName));
            predicate = predicate.AndIF(parm.Enabled != null, it => it.Enabled == parm.Enabled);
            return predicate;
        }
    }
}